package org.dsapr.codegen.processor.repository;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.google.auto.service.AutoService;
import com.squareup.javapoet.ClassName;
import com.squareup.javapoet.ParameterizedTypeName;
import com.squareup.javapoet.TypeSpec;
import org.dsapr.codegen.common.AutoGenerateRepository;
import org.dsapr.codegen.common.BaseGenerateProcessor;
import org.dsapr.codegen.common.CodeGenerateProcessor;
import org.dsapr.codegen.model.NameContext;

import javax.annotation.processing.RoundEnvironment;
import javax.lang.model.element.Modifier;
import javax.lang.model.element.TypeElement;
import java.io.File;
import java.lang.annotation.Annotation;
import java.nio.file.Path;
import java.nio.file.Paths;

@AutoService(value = CodeGenerateProcessor.class)
public class RepositoryAutoGenerateProcessor extends BaseGenerateProcessor {
	private static final String CODEGEN_INFO = buildMessage();

	@Override
	public void generateClass(TypeElement typeElement, RoundEnvironment roundEnvironment) throws Exception {
		NameContext context = NameContext.builder().build(typeElement);
		String className = context.getRepositoryClassName();
		TypeSpec.Builder typeSpecBuilder = TypeSpec.interfaceBuilder(className)
				.addJavadoc(CODEGEN_INFO)
				.addSuperinterface(ParameterizedTypeName.get(ClassName.get(BaseMapper.class), ClassName.get(context.getEntityPackageName(), context.getClassName())))
				.addModifiers(Modifier.PUBLIC);

		Path srcPath = Paths.get(typeElement.getAnnotation(AutoGenerateRepository.class).sourcePath());
		File srcAbsoluteFile = srcPath.toFile().getAbsoluteFile();
		if (srcAbsoluteFile.exists()) {
			File sourceFile = new File(srcAbsoluteFile.getAbsolutePath(), context.getControllerClassName() + ".java");
			if (!sourceFile.exists()) {
				writeJavaFile(getPackage(typeElement), typeSpecBuilder.build(), srcAbsoluteFile.getAbsolutePath());
			}
		}
	}

	@Override
	public Class<? extends Annotation> getAnnotation() {
		return AutoGenerateRepository.class;
	}

	@Override
	public String getPackage(TypeElement typeElement) {
		return typeElement.getAnnotation(AutoGenerateRepository.class).packageName();
	}
}
